from rest_framework.permissions import BasePermission
from rest_framework import permissions as per
from users.models import User

# has_permission 是用户对这个视图有没有 GET POST PUT PATCH DELETE 权限的分别判断
class IsHasPermission(BasePermission):
    def has_permission(self, request, view):
        # 管理员对用户模型有访问权
        if request.user.is_superuser:
            return True
        # 获取用户操作的模型
        model_name = request.resolver_match.url_name.split('-')[0]
        codename = None
        # 如果操作方法为删除，则将操作关键字改为删除
        if request.method == 'DELETE':
            codename = f'delete_{model_name}'
        # 如果操作方法为post，则将操作关键字改为新增
        elif request.method == 'POST':
            codename = f'add_{model_name}'
        # 如果操作方法为put或patch，则将操作关键字改为修改
        elif request.method in ['PUT','PATCH']:
            codename = f'change_{model_name}'
        # 如果操作方法为get，则将操作关键字改为查询
        elif request.method == 'GET':
            codename = f'view_{model_name}'             
        permissions = self.get_object_permissions(request)
        return codename in permissions
    
    # 通过用户对应的组，组对应的权限，获取用户的全部权限列表
    def get_object_permissions(self, request):
        return list(User.objects.filter(
            id=request.user.id, status=1).values_list('groups__permissions__codename', flat=True))


class IsOwnerPermission(BasePermission):
    # has_object_permission 是用户过了 has_permission 判断有权限以后，再判断这个用户有没有对一个具体的对象有没有操作权限
    # 这样设置以后，即使是django admin管理员也只能查询自己user标的信息，不能查询其他用户的单条信息
    def has_object_permission(self, request, view, obj):
        # 管理员对用户模型有访问权
        if request.user.is_superuser:
            return True
        # 安全访问有访问权
        if request.method in per.SAFE_METHODS:
            return True
        """获取单个数据时,判断用户对某个数据对象是否有访问权限"""
        # 自己建立的有访问权
        if request.user.id == obj.creator.split(',')[0]:
            return True
        # 设定有权限的有访问权限
        codename = request.resolver_match.url_name.split('-')[0]
        if request.method == "DELETE":
            codename = f'delete_{codename}'
        elif request.method == "GET":
            codename = f'view_{codename}'
        elif request.method == "POST":
            codename = f'add_{codename}'
        elif request.method in ["PUT", "PATCH"]:
            codename = f'change_{codename}'
        permissions = IsHasPermission().get_object_permissions(request)
        return codename in permissions